<?php

namespace App\Models\Admin\User;

class UserAuthorityModel extends BaseUserModel
{
    protected $table = 'user_authority';

    /**
     * 根据用户id查询角色ids
     *
     * @param int $userId
     * @return array
     */
    public function getAuthorityIdsByUserId(int $userId): array
    {
        return $this->where('user_id', $userId)
                    ->pluck('authority_id')
                    ->toArray();
    }

    /**
     * 根据用户ids查询数据
     *
     * @param array $userIds
     * @param array $fields
     * @return array
     */
    public function getItemsByUserIds(array $userIds, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->whereIn('user_id', $userIds)
                    ->get()
                    ->toArray();
    }

    /**
     *  根据角色 id 获取数据
     *
     * @return void
     */
    public function getItemByAuthorityId(int $authorityId, array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        return $this->select($fields)
                    ->where('authority_id', $authorityId)
                    ->get()
                    ->toArray();
    }

    /**
     * 根据userIds删除数据
     *
     * @param int $userId 用户id
     * @return int
     */
    public function deleteItemByUserId(int $userId): int
    {
        return $this->where('user_id', $userId)->delete();
    }

    /**
     * @param array $params
     * @return int
     */
    public function addItem(array $params): int
    {
        if (isset($params[0]) && is_array($params[0])) {
            foreach ($params as $index => $item) {
                $params[$index]['created_at'] = date('Y-m-d H:i:s');
            }
        } else {
            $params['created_at'] = date('Y-m-d H:i:s');
        }

        return $this->insert($params);
    }
}
